﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    networkParameters para = {"10.3.0.36", 777};

    ModbusTcpBasicInformation basicInfo = {1, 0, 6, 1, 1, 1, 1};

    p = new ModbusTCP(para);

    //按下连接控制按钮触发连接或者断开
    connect(ui->connectButton, &QPushButton::clicked,this,&Widget::TcpConnect);
    //按下发送按钮触发TCP主站请求报文函数
    connect(ui->sendButton,&QPushButton::clicked, [=](){
        p->TCPRequestMessageSend(basicInfo);
    });

    //当有可读数据时触发的槽函数
    connect(p, SIGNAL(receiveSuccess()), this, SLOT(showReceiveMessage()));

}

//1. TCP连接函数,按下按钮触发连接或断开
void Widget::TcpConnect()
{
    //判断当前是等待连接状态还是已连接状态
    if(ui->connectButton->text() == "连接")
    {
        p->Connect();
        ui->connectButton->setText("断开");

    }
    else
    {
        p->DisConnect();
        ui->connectButton->setText("连接");
    }
}

void Widget::showReceiveMessage()
{
    QByteArray aa;
    QString bb;
    p->GetReceiveMessage(aa);

    p->HexByteArrayToHexString(aa, aa.size(), bb);
    ui->message->append(bb);
    ui->message->moveCursor(QTextCursor::End);
}



Widget::~Widget()
{
    delete ui;
}

